package components

import (
	"context"
	"gopkg.in/olivere/elastic.v5"
)

type Elastic struct {
	Client *elastic.Client
	Index  string
	Type   string
}

func (e *Elastic) New(host ...string) (err error) {
	e.Client, err = elastic.NewClient(elastic.SetSniff(false), elastic.SetURL(host...))
	if err != nil {
		// Handle error
		panic(err)
	}
	return
}

func (e *Elastic) Push(body interface{}) (rsp *elastic.IndexResponse, err error) {
	rsp, err = e.Client.Index().Index(e.Index).Type(e.Type).BodyJson(body).Do(context.Background())
	return
}

func (e *Elastic) GetById(id string) (rsp *elastic.GetResult, err error) {
	rsp, err = e.Client.Get().Index(e.Index).Type(e.Type).Id(id).Do(context.Background())
	return
}

func (e *Elastic) Search(q *elastic.QueryStringQuery, offset int, limit int) (rsp *elastic.SearchResult, err error) {
	rsp, err = e.Client.Search().Index(e.Index).Type(e.Type).Query(q).Pretty(true).From(offset).Size(limit).Do(context.Background())
	return
}
